//
//  TTWaterflowerView.m
//  瀑布流练习
//
//  Created by 田涛 on 2017/3/13.
//  Copyright © 2017年 Lemon. All rights reserved.
//

#import "TTWaterflowerView.h"
#import "TTWaterflowerViewCell.h"

#define DefaultCellHeight 60
#define DefaultMargin 10
#define DefaultNumberOfColumns 3

@interface TTWaterflowerView ()
@property (nonatomic, strong) NSMutableArray *cellFrames;
@property (nonatomic, strong) NSMutableDictionary *showingCells;
@property (nonatomic, strong) NSMutableSet *reusableCells;
@end

@implementation TTWaterflowerView
@dynamic delegate;

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
    }
    return self;
}

#pragma mark  第一次出现时刷新数据
- (void)willMoveToSuperview:(UIView *)newSuperview {
    [self reloadData];
}

/** 刷新数据*/
- (void)reloadData {
    // cell 的总数
    NSUInteger numberOfCells = [self.dataSource numberOfCellsInWaterflowerView:self];
    
    // cell 的列数
    NSUInteger numberOfColumns = [self.dataSource respondsToSelector:@selector(numberOfColumnsInWaterflowerView:)] ? [self.dataSource numberOfColumnsInWaterflowerView:self] : DefaultNumberOfColumns;
    
    // 间距
    CGFloat topM = [self.delegate respondsToSelector:@selector(waterflowerView:marginForType:)] ? [self.delegate waterflowerView:self marginForType:TTWaterflowerViewMarginTypeTop] : DefaultMargin;
    CGFloat leftM = [self.delegate respondsToSelector:@selector(waterflowerView:marginForType:)] ? [self.delegate waterflowerView:self marginForType:TTWaterflowerViewMarginTypeLeft] : DefaultMargin;
    CGFloat bottomM = [self.delegate respondsToSelector:@selector(waterflowerView:marginForType:)] ? [self.delegate waterflowerView:self marginForType:TTWaterflowerViewMarginTypeBottom] : DefaultMargin;
    CGFloat rightM = [self.delegate respondsToSelector:@selector(waterflowerView:marginForType:)] ? [self.delegate waterflowerView:self marginForType:TTWaterflowerViewMarginTypeRight] : DefaultMargin;
    CGFloat columnM = [self.delegate respondsToSelector:@selector(waterflowerView:marginForType:)] ? [self.delegate waterflowerView:self marginForType:TTWaterflowerViewMarginTypeColumn] :DefaultMargin;
    CGFloat rowM = [self.delegate respondsToSelector:@selector(waterflowerView:marginForType:)] ? [self.delegate waterflowerView:self marginForType:TTWaterflowerViewMarginTypeRow] : DefaultMargin;
    
    // cell 的宽度
    CGFloat cellW = (self.bounds.size.width - leftM - rightM - (numberOfColumns - 1)* columnM) / numberOfColumns;
    
    // 用数组存放所有列的最大值
    NSMutableArray *maxYColumnArr = [NSMutableArray array];
    for (int i = 0 ; i < numberOfColumns; i ++) {
        [maxYColumnArr addObject:@"0"];
    }
    
    // 计算每个 cell 的 frame
    for (int i = 0; i < numberOfCells; i ++) {
        
        // 当前列
        NSUInteger currentColumn = 0;
        
        // 列最大Y值
        CGFloat maxYOfCellColumn = [maxYColumnArr[0] floatValue];
        
        for (int j = 1 ; j < numberOfColumns; j ++) {
            
            if ([maxYColumnArr[j] floatValue] < maxYOfCellColumn) {
                currentColumn = j;
                maxYOfCellColumn = [maxYColumnArr[j] floatValue];
            }
            
        }
        
        // 第i个cell的高度
        CGFloat cellH = [self.delegate respondsToSelector:@selector(waterflowerView:heightAtIndex:)] ? [self.delegate waterflowerView:self heightAtIndex:i] : DefaultCellHeight;
        CGFloat cellY = 0.0;
        
        // cell 的位置
        if (maxYOfCellColumn == 0.0) {
            cellY = topM;
        } else {
            cellY = maxYOfCellColumn + rowM;
        }
        
        // cell 的 X
        CGFloat cellX = leftM + (cellW + columnM) * currentColumn;
        
        // cell 的 frame 加入数组
        CGRect cellFrame = CGRectMake(cellX, cellY, cellW, cellH);
        [self.cellFrames addObject:[NSValue valueWithCGRect:cellFrame]];
        
        // 更新maxYOfColumnArr
        [maxYColumnArr replaceObjectAtIndex:currentColumn withObject:[NSString stringWithFormat:@"%lf",CGRectGetMaxY(cellFrame)]];
    }
    
    // 设置 ContentSize
    CGFloat contentH = [maxYColumnArr[0] floatValue];
    
    for (int i = 0; i < numberOfColumns; i++) {
        
        if (contentH < [maxYColumnArr[i] floatValue]) {
            contentH = [maxYColumnArr[i] floatValue];
        }
    }
    
    contentH += bottomM;
    self.contentSize = CGSizeMake(0, contentH);
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    NSUInteger numberOfCells = self.cellFrames.count;
    
    for (int i = 0; i < numberOfCells; i++) {
        
        
        
        CGRect cellFrame = [self.cellFrames[i] CGRectValue];
        TTWaterflowerViewCell *cell = self.showingCells[@(i)];
        
        if ([self isInScreen:cellFrame]) {
            if (cell == nil) {
                cell = [self.dataSource waterflowerView:self cellAtIndex:i];
                cell.frame = cellFrame;
                cell.backgroundColor = [UIColor redColor];
                [self addSubview:cell];
                self.showingCells[@(i)] = cell;
            }
        } else {
            if (cell) {
                [self.reusableCells addObject:cell];
                [cell removeFromSuperview];
                [self.showingCells removeObjectForKey:@(i)];
                cell = nil;
            }
        }

        
        
    }
}

/** Cell的宽度*/
- (CGFloat)cellWidth {
    
    CGFloat numberOfColumns = [self.dataSource respondsToSelector:@selector(numberOfColumnsInWaterflowerView:)] ? [self.dataSource numberOfColumnsInWaterflowerView:self] : DefaultNumberOfColumns;
    CGFloat leftM = [self.delegate respondsToSelector:@selector(waterflowerView:marginForType:)] ? [self.delegate waterflowerView:self marginForType:TTWaterflowerViewMarginTypeLeft] : DefaultMargin;
    CGFloat rightM = [self.delegate respondsToSelector:@selector(waterflowerView:marginForType:)] ? [self.delegate waterflowerView:self marginForType:TTWaterflowerViewMarginTypeRight] : DefaultMargin;
    CGFloat columnM = [self.delegate respondsToSelector:@selector(waterflowerView:marginForType:)] ? [self.delegate waterflowerView:self marginForType:TTWaterflowerViewMarginTypeColumn] : DefaultMargin;
    CGFloat cellW = (self.bounds.size.width - leftM - rightM - (columnM * numberOfColumns)) / numberOfColumns;
    return cellW;
}

/** 去缓存池查找可循环利用的Cell*/
- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier {
    
    __block TTWaterflowerViewCell *reusableCell = nil;
    
    [self.reusableCells enumerateObjectsUsingBlock:^(TTWaterflowerViewCell *cell, BOOL *stop) {
        if ([cell.identifier isEqualToString:identifier]) {
            reusableCell = cell;
            *stop = YES;
        }
    }];
    
    if (reusableCell) {
        [self.reusableCells removeObject:reusableCell];
    }
    
    return reusableCell;
}



/** 选中 cell*/
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    if (![self.delegate respondsToSelector:@selector(waterflowerView:didSelectedAtIndex:)]) {
        return;
    }
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    __block NSNumber *selectIndex = nil;
    [self.showingCells enumerateKeysAndObjectsUsingBlock:^(id key , TTWaterflowerViewCell *cell , BOOL *stop) {
        if (CGRectContainsPoint(cell.frame, point)) {
            selectIndex = key;
            *stop = YES;
        }
    }];
    if (selectIndex) {
        [self.delegate waterflowerView:self didSelectedAtIndex:selectIndex.unsignedIntegerValue];
    }
}

- (BOOL)isInScreen:(CGRect)frame {
    return (CGRectGetMaxY(frame) > self.contentOffset.y) && (CGRectGetMinY(frame) < self.contentOffset.y + self.frame.size.height);
}

#pragma mark - 懒加载
- (NSMutableArray *)cellFrames {
    if (!_cellFrames) {
        _cellFrames = [NSMutableArray array];
    }
    return _cellFrames;
}

- (NSMutableDictionary *)showingCells {
    if (!_showingCells) {
        _showingCells = [NSMutableDictionary dictionary];
    }
    return _showingCells;
}

- (NSMutableSet *)reusableCells {
    if (!_reusableCells) {
        _reusableCells = [NSMutableSet set];
    }
    return _reusableCells;
}

@end
